﻿namespace CamlQueryCreator.Common
{
    /// <summary>
    /// Оператор "DateRangesOverlap" CAML-запроса.
    /// </summary>
    public sealed class CamlOperatorDateRangesOverlap : CamlOperator
    {
        private const string QUERY_WITH_RECURRENCE_FORMAT = "<DateRangesOverlap>{0}<FieldRef Name='RecurrenceID'/><Value Type='DateTime'><Month /></Value></DateRangesOverlap>";
        private const string QUERY_WITHOUT_RECURRENCE_FORMAT = "<DateRangesOverlap>{0}<Value Type='DateTime'><Month /></Value></DateRangesOverlap>";
        private const string FIELD_REF_FORMAT = "<FieldRef Name='{0}'/>";

        private readonly string _startDateFieldName;
        private readonly string _endDateFieldName;
        private readonly bool _isRecurrence;

        /// <summary>
        /// Оператор "DateRangesOverlap" CAML-запроса.
        /// <para>Конструктор.</para>
        /// </summary>
        public CamlOperatorDateRangesOverlap(CamlConnector parentBuilder, string startDateFieldName, string endDateFieldName, bool isRecurrence): base(parentBuilder)
        {
            _startDateFieldName = startDateFieldName;
            _endDateFieldName = endDateFieldName;
            _isRecurrence = isRecurrence;
        }

        protected override string GetQuery(string childQuery)
        {
            var fieldRefs = string.Format(
                "{0}{1}",
                GetFieldRef(_startDateFieldName),
                GetFieldRef(_endDateFieldName));

            var format = _isRecurrence
                             ? QUERY_WITH_RECURRENCE_FORMAT
                             : QUERY_WITHOUT_RECURRENCE_FORMAT;

            return string.Format(format, fieldRefs);
        }

        private static string GetFieldRef(string fieldName)
        {
            return string.Format(FIELD_REF_FORMAT, fieldName);
        }
    }
}
